

class AppDateUtil {
  const AppDateUtil._();

  /// 日期格式化
  static String dateFormat(dynamic input, [fmt = 'YYYY-MM-DD HH:mm:ss']) {
    DateTime date = DateTime.now();

    if (input is String) {
      date = DateTime.parse(input);
    } else if (input is int) {
      date = DateTime.fromMillisecondsSinceEpoch(input);
    } else if (input is DateTime) {
      date = input;
    }

    Map<String, String> o = {
      'YYYY': date.year.toString(),
      'YY': date.year.toString().substring(2),
      'MM': date.month.toString().padLeft(2, '0'),
      'M': date.month.toString(),
      'DD': date.day.toString().padLeft(2, '0'),
      'D': date.day.toString(),
      'HH': date.hour.toString().padLeft(2, '0'),
      'H': date.hour.toString(),
      'hh': (date.hour > 12 ? date.hour - 12 : date.hour).toString().padLeft(0, '0'),
      'h': (date.hour > 12 ? date.hour - 12 : date.hour).toString(),
      'mm': date.minute.toString().padLeft(2, '0'),
      'm': date.minute.toString(),
      'ss': date.second.toString().padLeft(2, '0'),
      's': date.second.toString(),
      'S': date.millisecond.toString(),
      'a': date.hour >= 12 ? 'pm' : 'am',
      'A': date.hour >= 12 ? 'PM' : 'AM',
    };

    o.forEach((key, value) {
      fmt = fmt.replaceAll(key, value);
    });

    return fmt;
  }

  /// 过去时间友好提示
  /// https://blog.csdn.net/qq_42740797/article/details/114930843
  static String formatPastTime(DateTime input) {
    String fmt = '';

    final now = DateTime.now();
    final diff = now.difference(input);

    if (((now.year - input.year == 1 || now.month - input.month == 1) && diff.inHours >= 0 && diff.inHours <= 24) ||
        now.day - input.day >= 1) {
      // 昨天 HH:mm
      fmt = dateFormat(input, '昨天 HH:mm');
    } else if (now.year - input.year >= 1) {
      // YYYY-MM-DD HH:mm
      fmt = dateFormat(input, 'YYYY-MM-DD HH:mm');
    } else if (now.month - input.month >= 1 || now.day - input.day >= 2) {
      // MM-DD AM/PM HH:mm
      fmt = dateFormat(input, 'MM-DD A HH:mm').replaceAll('AM', '上午').replaceAll('PM', '下午');
    } else if (now.hour - input.hour >= 1) {
      // HH:mm
      fmt = dateFormat(input, 'HH:mm');
    }

    return fmt;
  }
}
